import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter_base/page/common/loading_toast.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

///
/// @DIR_PATH：lib/page/common
/// @TIME：2024/6/22 18:34
/// @AUTHOR：starr
///

///需要加载的内容类型
enum WebViewType {
  HTML,
  URL,
}

//定义js通信回调
typedef dynamic JsChannelCallback(List<dynamic> argument);

class WebViewWidget extends StatefulWidget {
  const WebViewWidget(
      {super.key,
      required this.webViewType,
      required this.loadResource,
      this.jsChannelMap,
      this.onWebViewCreated,
      this.clearCache});

  //需要加载的内容类型
  final WebViewType webViewType;

  //需要加载的内容
  final String loadResource;

  //是否清除缓存再加载
  final bool? clearCache;

  //与js通信的channel集合
  final Map<String, JsChannelCallback>? jsChannelMap;

  //提供接口，供外部自定义实现webview的加载逻辑
  final Function(InAppWebViewController controller)? onWebViewCreated;

  @override
  State<StatefulWidget> createState() {
    return _WebViewWidgetState();
  }
}

class _WebViewWidgetState extends State<WebViewWidget> {
  late InAppWebViewController webViewController;
  final GlobalKey webviewKey = GlobalKey();

  //因为flutter_inappwebview是基于分别在android和ios下基于原生实现的
  //所以需要分别对两个平台做一个区别配置
  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      //跨平台配置,两个平台下都会生效
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true,
        mediaPlaybackRequiresUserGesture: false,
      ),
      //安卓平台下的配置
      android: AndroidInAppWebViewOptions(
          builtInZoomControls: false, //不允许缩放
          useHybridComposition: true //支持Hybrid
          ),
      //IOS平台下的配置
      ios: IOSInAppWebViewOptions(allowsInlineMediaPlayback: true));

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return InAppWebView(
      key: webviewKey,
      initialOptions: options,
      onWebViewCreated: (controller) {
        webViewController = controller;
        //是否清除缓存再加载
        if (widget.clearCache == true) {
          controller.clearCache();
        }

        if (widget.onWebViewCreated == null) {
          if (widget.webViewType == WebViewType.HTML) {
            webViewController.loadData(data: widget.loadResource);
          } else if (widget.webViewType == WebViewType.URL) {
            webViewController.loadUrl(
                urlRequest: URLRequest(url: Uri.parse(widget.loadResource)));
          }
        } else {
          widget.onWebViewCreated?.call(controller);
        }

        //注册与js通信回调
        widget.jsChannelMap?.forEach((handlerName, callback) {
          webViewController.addJavaScriptHandler(
              handlerName: handlerName, callback: callback);
        });
      },
      onConsoleMessage: (controller, consoleMessage) {
        log("consoleMessage ====来自与js的打印==== \n $consoleMessage");
      },
      onProgressChanged: (InAppWebViewController controller, int progress) {},
      onLoadStart: (InAppWebViewController controller, Uri? url) {
        Loading.show(duration:const Duration(seconds: 5));
      },
      onLoadStop: (InAppWebViewController controller, Uri? url) {
        Loading.dismissAll();
      },
      onLoadError: (InAppWebViewController controller, Uri? url, int code,
          String message) {
        Loading.dismissAll();
      },
      onPageCommitVisible: (InAppWebViewController controller, Uri? url) {},
    );
  }

  @override
  void dispose() {
    super.dispose();
    Loading.dismissAll();
  }
}
